<?php
require_once 'vendor/autoload.php';

require_once 'Smtp.class.php';

/**
 * 消息推送驱动器组件：Eml.SmtpEmail[消息子模型-EML.通用的SMTP!]
 * 
 * @date	2017年7月19日 下午7:30:22
 * 
 */
class MessagePusherEml_SmtpEmail extends CI_Driver implements libraries\common\MessagePusherInterface
{
	const DEBUG_MODE = false;
	private $smtpServer = ""; 	// SMTP服务器
	private $smtpPort = 25; 	// SMTP服务器端口
	private $smtpUser = ""; 	// SMTP服务器的用户帐号
	private $smtpPass = ""; 	// SMTP服务器的用户密码
	private $fromMail = ""; 	// SMTP服务器的用户邮箱
	private $mailType = 'HTML';	// 邮件格式（HTML/TXT）,TXT为文本邮件
	
	private $lastResponse       = null;
	
	public function __set($var, $val)
	{
		$this->$var = $val;
	}
	
	public function __construct($config = array())
	{
		
	}
	
	/**
	 * 给定数据执行推送
	 *
	 * @param array $data
	 *
	 * @return void
	 */
	public function pushPerform($data)
	{
		if(self::DEBUG_MODE) {
			return ;
		}
		$toEmail = $data['email'];
		$subject = $data['subject'];
		$message = $data['msg'];
		$this->lastResponse = $this->send($toEmail, $subject, $message);
	}
	
	/**
	 * 获取上一次推送的状态
	 *
	 * @return boolean
	 */
	public function getStatus()
	{
		if(self::DEBUG_MODE) {
			return true;
		}
		$response = $this->getParsedResponse();
		if($response == true) {
			return true;
		}
		
		return false;
	}
	
	public function getMessage()
	{
		$response = $this->getParsedResponse();
		if($response) {
			return 'success';
		}
		
		return false;
	}
	
	private function send($toMail, $subject, $message)
	{
		//新建SMTP实例
		$smtp = new Smtp($this->smtpServer, $this->smtpPort, $isauth = true, $this->smtpUser, $this->smtpPass);
		
		//是否显示发送的调试信息
		//$smtp->debug = self::DEBUG_MODE;
		$smtp->debug = false; // 不能使用 self::DEBUG_MODE，否则根本执行不到这儿！
		
		$from = $this->fromMail;
		$to = $toMail;
		$body = $message;
		//发送邮件
		$state = $smtp->sendmail($to, $from, $subject, $body, $this->mailType);
		return  $state;
	}
	
	private function getParsedResponse()
	{
		if(!isset($this->lastResponse)) {
			trigger_error(sprintf("%s::%s: You Shouldn't call me here, because no response now!", __CLASS__, __METHOD__), E_USER_ERROR);
			return false;
		}
		
		$response = $this->lastResponse;
		
		//print_r($response);
		return $response;
	}
	
}

